package com.xbts.common.utils.aspose;

import com.aspose.cells.License;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 * CellsFileConvert
 *
 * @author swx
 * @version v1.0
 * @date 2022/10/27 17:24
 */
@Component
public class CellsFileConvert implements IFileConvert {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    private boolean getLicense() {
        boolean result = false;
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        try (InputStream is = loader.getResourceAsStream("license.xml")) {
            License license = new License();
            license.setLicense(is);
            result = true;
        } catch (Exception e) {
            log.error("获取license失败", e);
        }
        return result;
    }

    @Override
    public InputStream fileToPdf(InputStream inputStream) {
        {
            if (!getLicense()) {
                return null;
            }
            try {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                // 原始excel路径
                Workbook wb = new Workbook(inputStream);
                PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
                //缩放到一个页面（如果列太多 太长）
                pdfSaveOptions.setOnePagePerSheet(true);
                //** 自动缩放了
                int[] autoDrawSheets = {3};
                //当excel中对应的sheet页宽度太大时，在PDF中会拆断并分页。此处等比缩放。
                autoDraw(wb, autoDrawSheets);
                //隐藏workbook中不需要的sheet页。
                printSheetPage(wb);
                wb.save(byteArrayOutputStream, pdfSaveOptions);
                return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            } catch (Exception e) {
               log.error("excel转pdf失败", e);
            }
            return null;
        }
    }

    /**
     * @param wb   设置打印的sheet自动拉伸比例
     * @param page 自动拉伸的页的sheet数组
     */
    public static void autoDraw(Workbook wb, int[] page) {
        if (null != page && page.length > 0) {
            for (int i = 0; i < page.length; i++) {
                wb.getWorksheets().get(i).getHorizontalPageBreaks().clear();
                wb.getWorksheets().get(i).getVerticalPageBreaks().clear();
            }
        }
    }

    /**
     * 显示workbook所有sheet页。
     *
     * @param wb
     */
    public static void printSheetPage(Workbook wb) {
        for (int i = 1; i < wb.getWorksheets().getCount(); i++) {
            wb.getWorksheets().get(i).setVisible(true);
        }
    }

    @Override
    public void afterPropertiesSet() {
        FileConvertConstant.EXCELS_TO_PDF.forEach(excel -> AsposeSingleton.instance().put(excel, this));
    }

}
